package com.defangit.award.extend.wxmp.config;

import com.defangit.award.domain.WinningInfo;
import com.defangit.award.extend.wxmp.domain.AwardUser;
import com.defangit.award.extend.wxmp.domain.UserGift;
import com.defangit.award.extend.wxmp.domain.WxmpUser;
import com.defangit.award.extend.wxmp.orm.WxmpUserGiftService;
import com.defangit.award.extend.wxmp.orm.WxmpUserService;
import com.defangit.award.orm.HibernateUtil;
import com.defangit.award.orm.WinningInfoService;
import com.defangit.openapis.wechat.mp.care.domain.CareMessage;
import com.defangit.openapis.wechat.mp.care.domain.WxcardCareMessage;
import com.defangit.openapis.wechat.mp.message.req.RequestMessage;
import com.defangit.openapis.wechat.mp.message.req.TextMessage;
import com.defangit.openapis.wechat.mp.message.req.event.ScanEvent;
import com.defangit.openapis.wechat.mp.message.req.event.SubscibeEvent;
import com.defangit.openapis.wechat.mp.message.req.event.UnSubscribeEvent;
import com.defangit.openapis.wechat.mp.message.resp.ResponseMessage;
import com.defangit.openapis.wechat.mp.message.resp.TextResponse;
import com.defangit.opens.wechat.TenpayGiftPacket;
import com.defangit.opens.wechat.WxPayConfig;
import laogen.util.StringUtil;
import laogen.util.UniqueNoBuilder;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Subqueries;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * Created by zhangfagen on 2019/1/14.
 */
public class ZmWxmpConfig extends AwardWxmpConfig {
    private static WxPayConfig payConfig=new WxPayConfig()
            .setAppId("wx6971f11ba837964d")
            .setKey("BQ7M2kojuQ4QM9NLSGaMgg3Qc1dJAIuK")
            .setMerchantId("1522869541");
    private UniqueNoBuilder noBuilder=UniqueNoBuilder.getInstance("tenpay.gift",ls->{

    });
    public ZmWxmpConfig(){
        super("zm");
        setAppId("wx6971f11ba837964d").setSecret("4acbd0ea54923072d83bbe06177d9da5").setToken("jlg9M6q02SL1nazHP7V9euiAxUkkBP3A");
    }
    @Override
    public ResponseMessage handleMsg(RequestMessage msg) {
        if(msg instanceof UnSubscribeEvent){

        }else{
            new WxmpUserService().addUser(msg.getFromUserName(),getGh(),0);
        }



        ResponseMessage res=null;
        if (msg instanceof TextMessage) {
            res=awardByKey(msg.getFromUserName(),((TextMessage) msg).getContent());
        }

        if (msg instanceof ScanEvent) {//如果用户发送的信息是微信扫码事件
            try {
                String key=((ScanEvent) msg).getEventKey();
                res=awardByKey(msg.getFromUserName(),key);
            } catch (Exception ex) {
                System.out.println(ex);
            }
        }
        if (msg instanceof SubscibeEvent) {
            if(StringUtil.notEmpty(((SubscibeEvent) msg).getEventKey())){
                try {
                    String key=((SubscibeEvent) msg).getEventKey();
                    res=awardByKey(msg.getFromUserName(),key);
                } catch (Exception ex) {
                    System.out.println(ex);
                }
            }else{
                res=new TextResponse()
                        .setContent("感谢您关注!");
            }
        }
        if (msg instanceof UnSubscribeEvent) {
            try {

            } catch (Exception ex) {
                System.out.println(ex);
            }
        }
        if(res==null){
            res=new TextResponse()
                    .setContent("sorry,没搞懂您想要什么");
        }
        return res;
    }

    @Override
    protected ResponseMessage makeAttendedInfo(WinningInfo info) {
        if(info.getAwardId()==1){
//            Award award=new AwardService().get(info.getPrize().getId())
//                    .orElseThrow(()->
//                            ParameterNotValidException.zeroIdOrEntityNonExist("抽奖活动")
//                    );
            long cnt=new WinningInfoService().findAll()
                    .award(info.getAwardId()).count();
            long no=cnt/30;
//            LocalDate adate=LocalDate.now().minusDays(no);
            String txtResp="感谢您，已为您预约1月"+(23+no)+"日，第"+(no+1)+"场正蒙教育【高中高效学习方法】推介会。"
                    +System.lineSeparator()+"============"+System.lineSeparator()
                    +"请您于晚六点至新华书店西起航教育准时参会，现场抽奖有望获得新学期课程免单资格！"
                    +System.lineSeparator()+"============"+System.lineSeparator()
                    +"正蒙教育高中学习教练技术，半小时改变孩子一生的最后机会！"
                    +System.lineSeparator()+"============"+System.lineSeparator()
                    +"联系电话：0354-2727823 17503421119"
                    +System.lineSeparator()+"============"+System.lineSeparator()
                    +"有任何问题请在公众号留言，我们将及时回复您";
            return new TextResponse().setContent(txtResp);
        }
        return super.makeAttendedInfo(info);
    }

    public boolean bindUser(String openid,String key){
        Session session= HibernateUtil.INSTANCE.getSession();
        Pattern pattern= Pattern.compile("(.*)\\+(\\d{11})\\+(.*)");
        Matcher matcher=pattern.matcher(key);
        AwardUser usr=null;
        if(matcher.find()){
            String parent=matcher.group(1);
            String mobile=matcher.group(2);
            String name=matcher.group(3);
            usr=(AwardUser)session.createCriteria(AwardUser.class)
                    .add(Restrictions.eq("name",name))
                    .uniqueResult();
            if(usr==null){
                usr=new AwardUser().setName(name);
                session.save(usr);
            }
//
//            WxmpUser wUsr=()session.createCriteria(WxmpUser.class)
//                    .add(Restrictions.eq("info.openid",openid))
//                    .uniqueResult();
            return new WxmpUserService().addUser(openid,getGh(),usr.getId(),parent,mobile);
        }else{
            return false;
        }
    }

    @Override
    public ResponseMessage awardByKey(String openId, String key) {
        Pattern pattern= Pattern.compile(".*bind$");
        Matcher matcher=pattern.matcher(key);
        if(matcher.matches()){
            return new TextResponse().setContent("请绑定用户，格式：家长姓名+手机号+孩子姓名"+System.lineSeparator()+"如'张三+13313331333+张晓明'");
        }
        pattern=Pattern.compile(".*gift$");
        matcher=pattern.matcher(key);
        if(matcher.matches()){
            synchronized (ZmWxmpConfig.class) {
                int rnd=new Random().nextInt(3);
                CareMessage msg=null;
                switch (rnd){
                    case 0:
                        msg=new WxcardCareMessage("pgI0t1MsslnMXFoylQmNkgHrbEjo")
                                .setToUser(openId);
                        break;
                    case 1:
                        msg=new WxcardCareMessage("pgI0t1D48cVj4RpjJUlsgHikwnwo")
                                .setToUser(openId);
                        break;
                    case 2:
                        msg=new WxcardCareMessage("pgI0t1KndMSqpRqWlUFLSsL-i1_E")
                                .setToUser(openId);
                        break;
                }
                this.getWechat().careManager().sendCareMessage(msg);
                return new TextResponse().setContent("正蒙科技祝您猪年吉祥，已为您发送优惠卡券!" + System.lineSeparator() +
                        "==============="+"到店出示优惠券使用"
                        + System.lineSeparator() +
                        "==============="+System.lineSeparator()+"转发亲友共享优惠吧！");
            }
        }
        if(bindUser(openId,key)){
            Session session=HibernateUtil.INSTANCE.getSession();
            WxmpUser mpUser=(WxmpUser)session.createCriteria(WxmpUser.class)
                    .add(Restrictions.eq("info.openid",openId))
                    .uniqueResult();
            DetachedCriteria mchOpens=DetachedCriteria.forClass(WxmpUser.class)
                    .add(Restrictions.eq("userId",mpUser.getId()))
                    .setProjection(Projections.property("info.openid"));
            long cnt=(long)session.createCriteria(WinningInfo.class)
                    .add(Subqueries.propertyIn("openId",mchOpens))
                    .setProjection(Projections.rowCount())
                    .uniqueResult();
            if(cnt>0){
                return new TextResponse().setContent("您的孩子已报名抽奖，请勿重复报名！");
            }

            key="QZ4";
        }

        return super.awardByKey(openId, key);
    }
}
